import trackService from '@/services/track-service';
import {
  CalendarOutlined,
  ClockCircleOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  ReloadOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import {
  Alert,
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Form,
  InputNumber,
  Row,
  Space,
  Spin,
  Tabs,
  Tag,
  Typography,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import './index.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Text } = Typography;

interface ClusterManagementProps {
  shouldPoll?: boolean;
}

const ClusterManagement: React.FC<ClusterManagementProps> = ({
  shouldPoll = true,
}) => {
  const [status, setStatus] = useState({
    isRunning: false,
    isLocked: false,
    loading: false,
  });
  const [intervalMinutes, setIntervalMinutes] = useState(60);
  const [schedulerEnabled, setSchedulerEnabled] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState('quick');
  const [form] = Form.useForm();

  // 获取当前状态
  const fetchStatus = async () => {
    try {
      setStatus((prev) => ({ ...prev, loading: true }));
      const rawData = await trackService.cluster_status();
      const res = rawData.data;
      if (res.code === 0) {
        setStatus({
          isRunning: res.data.is_running,
          isLocked: res.data.is_locked,
          loading: false,
        });
        setSchedulerEnabled(res.data.is_running);
      }
    } catch (error) {
      message.error('获取状态失败: ' + error.message);
      setStatus((prev) => ({ ...prev, loading: false }));
    }
  };

  useEffect(() => {
    fetchStatus(); // 初始加载

    let intervalId: NodeJS.Timeout;
    if (shouldPoll) {
      intervalId = setInterval(fetchStatus, 10000);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [shouldPoll]);

  // 立即执行全量聚类
  const handleRunFull = async () => {
    setIsSubmitting(true);
    try {
      const rawData = await trackService.cluster_run_full();
      const res = rawData.data;
      if (res.code === 0) {
        message.success(res.message || '全量聚类任务已开始执行');
        fetchStatus();
      } else {
        message.warning(res.message || '操作执行失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 执行增量聚类
  const handleRunIncremental = async () => {
    setIsSubmitting(true);
    try {
      const rawData = await trackService.cluster_run_incremental();
      const res = rawData.data;
      if (res.code === 0) {
        message.success(res.message || '增量聚类任务已开始执行');
        fetchStatus();
      } else {
        message.warning(res.message || '操作执行失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 执行时间范围聚类
  const handleRunRange = async (values: any) => {
    setIsSubmitting(true);
    try {
      const [startDate, endDate] = values.dateRange;
      const rawData = await trackService.cluster_run_range({
        start_date: startDate.format('YYYY-MM-DD'),
        end_date: endDate.format('YYYY-MM-DD'),
      });
      const res = rawData.data;
      if (res.code === 0) {
        message.success(res.message || '时间范围聚类任务已开始执行');
        fetchStatus();
      } else {
        message.warning(res.message || '操作执行失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 启动定时任务
  const handleStartScheduler = async () => {
    setIsSubmitting(true);
    try {
      const rawData = await trackService.cluster_start_scheduler({
        interval_minutes: intervalMinutes,
      });
      const res = rawData.data;
      if (res.code === 0) {
        message.success(res.message || '定时任务已启动');
        setSchedulerEnabled(true);
        fetchStatus();
      } else {
        message.warning(res.message || '操作执行失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 停止定时任务
  const handleStopScheduler = async () => {
    setIsSubmitting(true);
    try {
      const rawData = await trackService.cluster_stop_scheduler();
      const res = rawData.data;
      if (res.code === 0) {
        message.success(res.message || '定时任务已停止');
        setSchedulerEnabled(false);
        fetchStatus();
      } else {
        message.warning(res.message || '操作执行失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="cluster-management">
      <Card
        title={
          <Space>
            <SyncOutlined />
            <span>聚类任务管理</span>
          </Space>
        }
        bordered={false}
        className="management-card"
      >
        <Spin spinning={status.loading}>
          <div className="status-section">
            <Row gutter={16}>
              <Col span={12}>
                <Card size="small" title="当前状态">
                  <Space size="large">
                    <div>
                      <Text type="secondary">调度器状态:</Text>
                      <Tag
                        color={status.isRunning ? 'green' : 'red'}
                        icon={
                          status.isRunning ? (
                            <PlayCircleOutlined />
                          ) : (
                            <PauseCircleOutlined />
                          )
                        }
                      >
                        {status.isRunning ? '运行中' : '已停止'}
                      </Tag>
                    </div>
                    <div>
                      <Text type="secondary">任务状态:</Text>
                      <Tag
                        color={status.isLocked ? 'orange' : 'blue'}
                        icon={
                          status.isLocked ? <ClockCircleOutlined /> : undefined
                        }
                      >
                        {status.isLocked ? '执行中' : '空闲'}
                      </Tag>
                    </div>
                  </Space>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="定时任务">
                  <Space>
                    <InputNumber
                      min={1}
                      max={1440}
                      value={intervalMinutes}
                      onChange={setIntervalMinutes}
                      disabled={schedulerEnabled}
                      addonBefore="间隔(分钟)"
                    />
                    {schedulerEnabled ? (
                      <Button
                        danger
                        icon={<PauseCircleOutlined />}
                        onClick={handleStopScheduler}
                        loading={isSubmitting}
                      >
                        停止定时
                      </Button>
                    ) : (
                      <Button
                        type="primary"
                        icon={<PlayCircleOutlined />}
                        onClick={handleStartScheduler}
                        loading={isSubmitting}
                      >
                        启动定时
                      </Button>
                    )}
                  </Space>
                </Card>
              </Col>
            </Row>
          </div>

          <Divider />

          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            className="cluster-tabs"
          >
            <TabPane
              tab={
                <span>
                  <ReloadOutlined />
                  快速聚类
                </span>
              }
              key="quick"
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                <Button
                  type="primary"
                  icon={<ReloadOutlined />}
                  onClick={handleRunIncremental}
                  loading={isSubmitting}
                  disabled={status.isLocked}
                  block
                >
                  执行增量聚类
                </Button>
                <Button
                  type="primary"
                  icon={<ReloadOutlined />}
                  onClick={handleRunFull}
                  loading={isSubmitting}
                  disabled={status.isLocked}
                  block
                  danger
                >
                  执行全量聚类
                </Button>
              </Space>
            </TabPane>
            <TabPane
              tab={
                <span>
                  <CalendarOutlined />
                  时间范围聚类
                </span>
              }
              key="range"
            >
              <Form form={form} onFinish={handleRunRange}>
                <Form.Item
                  name="dateRange"
                  label="选择时间范围"
                  rules={[{ required: true, message: '请选择时间范围' }]}
                >
                  <RangePicker
                    style={{ width: '100%' }}
                    disabledDate={(current) => current && current > new Date()}
                  />
                </Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<CalendarOutlined />}
                  loading={isSubmitting}
                  disabled={status.isLocked}
                  block
                >
                  执行时间范围聚类
                </Button>
              </Form>
            </TabPane>
          </Tabs>

          {status.isLocked && (
            <Alert
              message="聚类任务正在执行中，请勿重复操作"
              type="warning"
              showIcon
              className="alert-message"
              style={{ marginTop: 16 }}
            />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default ClusterManagement;
